package com.ljkj.zjf.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.ljkj.access.Tlog;
import com.ljkj.access.Tuser;
import com.ljkj.access.Tuserrightrelation;
import com.ljkj.common.db.dao.TuserDAO;
import com.ljkj.common.db.util.DateTime;
import com.ljkj.zjf.common.CacheManager;
import com.ljkj.zjf.common.GlobalNames;

public class TuserService {
	
	private TuserDAO tuserDAO;
	private TLogService tLogService;
	private TuserRightService tuserRightService;
	

	

	public String getTuserByProperties(String params,int currentPage,int pageSize,String sortField,String sortOrder){
		
		Class[] pojos = {Tuser.class};
		String[] propertyNames=null;
		Object[] values=null;
		String[] likePropertyNames = null;
		Object[] likevalues= null;
		String[] betweenPropertyNames=null;
		Object[][]  betweenvalues=null;
		String[] orderByPropertyNames=null;
		Object[] orderByValues=null;
		
		if(sortField != null){
			orderByPropertyNames = new String[]{sortField};
			orderByValues =  new String[]{sortOrder};
		}

		int count = this.tuserDAO.getCount(pojos, propertyNames, values,likePropertyNames, likevalues, betweenPropertyNames,betweenvalues);
		this.tuserDAO.setPageMaxCount(pageSize);
		List<Tuser> tusers = this.tuserDAO.findByProperties(pojos, propertyNames, values, likePropertyNames, likevalues, betweenPropertyNames, betweenvalues, orderByPropertyNames, orderByValues, currentPage);
		
		List<Object> entry_list = new ArrayList<Object>();
		//迭代遍历所有条目，放到map里
		for(Tuser tuser : tusers){
			
			Map<String,Object> entry_map = new HashMap<String,Object>();
			entry_map.put("tuId",tuser.getTuId());
			entry_map.put("loginName",tuser.getLoginName());
			entry_map.put("vsername",tuser.getVsername());
			entry_map.put("mobile",tuser.getMobile());
			entry_map.put("createTime", tuser.getCreateTime());
			entry_map.put("createUser", tuser.getCreateUser());
			entry_map.put("updateTime", tuser.getUpdateTime());
			entry_map.put("updateUser", tuser.getUpdateUser());
			entry_map.put("lastLoginTime", tuser.getLastLoginTime());
			entry_map.put("disabledState", tuser.getDisabledState());
			entry_map.put("count", tuser.getCount());
			entry_map.put("email", tuser.getEmail());
			
			entry_list.add(entry_map);
		}
		
		HashMap<String,Object> result_map = new HashMap<String, Object>();
		result_map.put("data", entry_list);
		result_map.put("total", count);
		
        return JSON.toJSONString(result_map);
	}
	
	/**
	 * 新增或编辑用户信息
	 * @param newUser
	 * @param tuser
	 * @param str_id
	 * @return
	 */
	public String addOrEditTuserInfo(Tuser newUser,Tuser tuser,String str_id){
		
		Tlog tlog = new Tlog();
		
		Map<String,String> result_map = new HashMap<String, String>();
		if(newUser.getTuId() == null){
			
			tlog.setOpType(1);
			tlog.setContent("新增管理员："+newUser.getLoginName());
			
			newUser.setCreateTime(DateTime.getDateTime());
			newUser.setCreateUser(tuser.getLoginName());
			if(this.saveNewTuser(newUser)){
				this.tLogService.addOrEditTlogInfo(tlog, tuser);
				result_map.put("err_msg", "新增成功。");
				result_map.put("err_code", "0");
			}else{
				result_map.put("err_msg", "新增失败。");
				result_map.put("err_code", "1");
			}
			
		}else{
			try{
				
				if(newUser.getDisabledState()!=null && newUser.getDisabledState() == 1){
					tlog.setOpType(0);
					tlog.setContent("禁用管理员："+newUser.getLoginName()+" 变为不可用");
				}else{
					tlog.setOpType(1);
					tlog.setContent("修改管理员信息："+newUser.getLoginName());
				}
				
				newUser.setUpdateTime(DateTime.getDateTime());
				newUser.setUpdateUser(tuser.getLoginName());
				this.tuserDAO.update(newUser);
				this.tLogService.addOrEditTlogInfo(tlog, tuser);
				result_map.put("err_msg", "更新成功。");
				result_map.put("err_code", "0");
			}catch(Exception ex){
				result_map.put("err_msg", "更新失败。");
				result_map.put("err_code", "1");
			}
		}
		
		if(str_id != null && !"".equals(str_id)){
			String[] ids = str_id.split(",");
			List<Tuserrightrelation> tuserrightrelations = new ArrayList<Tuserrightrelation>();
			for(String id : ids){
				if(!"".equals(id)){
					Integer id_int = Integer.valueOf(id);
					Tuserrightrelation tuserrightrelation = new Tuserrightrelation();
					tuserrightrelation.setRightType(1);
					tuserrightrelation.setTuId(newUser.getTuId());
					tuserrightrelation.setTrId(id_int);
					
					tuserrightrelations.add(tuserrightrelation);
				}
			}
			this.tuserRightService.deleteUserRightRelationByUserId(newUser.getTuId());
			this.tuserRightService.saveUserRightRelation(tuserrightrelations);
		}
		
		return JSON.toJSONString(result_map);
	}
	
	public boolean saveNewTuser(Tuser tuser){
		try{
			this.tuserDAO.save(tuser);
			return true;
		}catch(Exception ex){
			return false;
		}
	}
	
	
	/**
	 * 后台用户登录
	 * @param userName
	 * @param userPwd
	 * @return
	 */
	public String adminLogin(String userName,String userPwd) throws Exception{
		
		Map<String, Object> errorMap = new HashMap<String, Object>();
		errorMap.put("errCode", GlobalNames.CALL_RESULT_FAIL);
		
		List<Tuser>  tusers = this.tuserDAO.findByProperty("loginName", userName);
		if(tusers == null || tusers.size() == 0){
			errorMap.put("errMsg", "用户不存在");
			return JSON.toJSONString(errorMap);
		}
		
		for(Tuser tuser : tusers){
			if(userPwd.equals(tuser.getPassword())){
				errorMap.put("errCode", GlobalNames.CALL_RESULT_SUCC);
				errorMap.put("errMsg", "");
				
				tuser.setCount((tuser.getCount()==null?0:tuser.getCount())+1);
				tuser.setLastLoginTime(tuser.getLoginTime());
				tuser.setLoginTime(DateTime.getDateTime());
				this.tuserDAO.update(tuser);
				
		        CacheManager.getSession().get(String.valueOf(tuser.getTuId()));
		        errorMap.put("TuserID", tuser.getTuId());
				
				break;
			}else{
				errorMap.put("errMsg", "密码不正确");
			}
		}
	    System.out.println("===========================成功访问数据库==================================");
		return JSON.toJSONString(errorMap);
	}
	
	public Tuser getUserById(Integer userId){
		
		return this.tuserDAO.findById(userId);
	}


	
	//注入DAO
	public void setTuserDAO(TuserDAO tuserDAO) {
		this.tuserDAO = tuserDAO;
	}
	public void settLogService(TLogService tLogService) {
		this.tLogService = tLogService;
	}
	public void setTuserRightService(TuserRightService tuserRightService) {
		this.tuserRightService = tuserRightService;
	}
}
